import { isAbsoluteURL, showToast } from './index';
import useLoadingStore from "@/store/modules/loading";

// showLoading 是否展示loading 默认true
// hideLoading 是否关闭loading 默认true
// showToast 配置是否展示错误提示 默认true
// goLogin 配置是否未登录跳转登录 默认false
export default function request(options: any) {
  let optionsUrl = options.url;
  options.showToast = options.showToast !== false;
  if (!isAbsoluteURL(options.url)) {
    options.url = import.meta.env.VITE_BASE_API + options.url;
  }

  if (import.meta.env.VITE_showRequestLog == 'Y') {
    console.log(`${optionsUrl}入参`, options.data)
  }

  return new Promise((resolve, reject) => {
    const loadingStore = useLoadingStore();

    if (options.showLoading !== false) {
      uni.showLoading({
        title: '加载中...',
        mask: true,
        success() {
          options.timer = setTimeout(() => {
            try {
              uni.hideLoading();
            } catch(e) {}
          }, options.timeout || 10000)
        }
      })
    }

    uni.request({
      ...options,
      data: options.data,
      method: options.method || "post",
      timeout: options.timeout || 30000,
      success(res: any) {
        if (options.showLoading !== false && options.hideLoading !== false) {
          try {
            uni.hideLoading();
            loadingStore.setIsLoading(false);
          } catch(e) {}
          clearTimeout(options.timer);
        }
        const data = res.data;
        if (data.code === 0) {
          resolve(data);
        } else {
          data.data = data.data || {};
          reject(data);
        }
      },
      fail(error: any) {
        console.log('fail', error);
        if (options.showLoading !== false && options.hideLoading !== false) {
          try {
            uni.hideLoading();
            loadingStore.setIsLoading(false);
          } catch(e) {}
          clearTimeout(options.timer);
        }
        error.fail = true; // 增加标识，走fail分支，区分场景
        options.showToast && showToast('网络异常');
        reject(error);
      },
      complete() {
      }
    })
  })
}
